<template>
  <div class="container">
    <div class="app-container">

      <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      <el-table :data="list">
        <el-table-column align="center" width="200" label="id" prop="name">
          <template #default="obj">
            <span> {{ obj.$index +1 + pageParams.pagesize *(pageParams.page-1) }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="角色" prop="name">
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.name }}</div>
            <el-input v-else v-model="row.editRowData.name" />
          </template>

        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.state ? '已启用' : '未启用' }}</div>
            <el-switch v-else v-model="row.editRowData.state" :active-value="1" inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description">
          <template #default="{row}">
            <div v-if="!row.isEdit">{{ row.description }}</div>
            <el-input v-else v-model="row.editRowData.description" type="textarea" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="center">
          <template #default="{row}">
            <div v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="onshowPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="row.isEdit = true">编辑</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </div>
            <div v-else>
              <el-button size="mini" type="primary" @click="onUpdate(row)">确定</el-button>
              <el-button size="mini" @click="oncancel(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="formDate" label-width="120px" :model="formDate" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formDate.name" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item label="启用">
          <el-switch v-model="formDate.state" size="mini" active-value="1" inactive-value="0" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formDate.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>

              <el-button size="mini" @click="btnCancel">取消</el-button>

            </el-col>

          </el-row>

        </el-form-item>

      </el-form>

    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="permShow">
      <!--expand-on-click-node 关闭点击折叠节点  -->
      <!--show-checkbox 开启复选框   -->
      <!-- default-checked-keys 用来单独设置选中的节点 -->
      <!--  node-key="id" 告诉树id是唯一的 -->
      <!-- :check-strictly : 关闭父子联动  -->
      <!-- 怎么拿到用户选中节点，先绑定ref，在getCheckedKeys函数调用 -->
      <el-tree
        ref="treeRef"
        node-key="id"
        :default-checked-keys="checkPermIds"
        :check-strictly="true"
        show-checkbox
        :data="permList"
        default-expand-all
        :props="{label:'name'}"
        :expand-on-click-node="false"
      />
      <el-row :style="{ padding: '20px' }" type="flex" justify="center">
        <el-button size="mini" type="primary" @click="onAssignPerm">分配权限</el-button>
        <el-button size="mini" @click="permShow =false">取消</el-button>

      </el-row>
    </el-dialog>
  </div>

</template>
<script>
import { getPermissionListAPI } from '@/api/permission'
import { getRoleListAPI, addRoleAPI, updateRoleAPI, getRoleDetailAPI, assignPermAPI } from '@/api/role'
import { arrayToTree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      checkPermIds: [],
      permShow: false,
      permList: [],
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      formDate: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async onAssignPerm() {
      const checkedKeys = this.$refs.treeRef.getCheckedKeys()
      await assignPermAPI({ id: this.roleId, permIds: checkedKeys })
      this.$message.success('分配权限成功')
      this.permShow = false
    },
    async onshowPermission(id) {
      const res = await getPermissionListAPI()
      const { permIds } = await getRoleDetailAPI(id)
      this.roleId = id
      this.checkPermIds = permIds
      this.permList = arrayToTree(res)

      this.permShow = true
    },
    async getRoleList() {
      const res = await getRoleListAPI(this.pageParams)
      this.list = res.rows
      this.list.forEach(element => {
        this.$set(element, 'isEdit', false)
        this.$set(element, 'editRowData', {
          name: element.name,
          state: element.state,
          description: element.description
        })
      })
      this.pageParams.total = res.total
    },
    changePage(val) {
      this.pageParams.page = val
      console.log('val  ----->  ', val)

      this.getRoleList()
    },
    btnCancel() {
      this.$refs.formDate.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    async btnOK() {
      this.$refs.formDate.validate()
      console.log('  ----->  ', this.$refs.formDate.validate())
      // 引入的接口不需要用this，只有本组件的方法需要用this
      await addRoleAPI(this.formDate)
      this.$message.success('新增角色成功')
      this.getRoleList()
      this.btnCancel()
    },
    oncancel(row) {
      row.editRowData = {
        name: row.name,
        state: row.state,
        description: row.description
      }
      row.isEdit = false
    },
    async onUpdate(row) {
      if (!row.editRowData.name) return this.$message.error('角色名称不能为空')
      if (!row.editRowData.description) return this.$message.error('角色描述不能为空')

      await updateRoleAPI({ id: row.id, ...row.editRowData })
      this.$message.success('修改角色成功')
      this.getRoleList()
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
